<?php
namespace app\controller\recharge;

use app\BaseController;
use app\service\recharge\RechargeService;
use think\App;
use think\Response;

class Recharge extends BaseController
{
    protected $rechargeService;

    public function __construct(App $app, RechargeService $rechargeService)
    {
        parent::__construct($app);
        $this->rechargeService = $rechargeService;
    }

    /**
     * 获取充值套餐列表
     */
    public function getPackages()
    {
        try {
            $packages = $this->rechargeService->getPackageList();
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $packages
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 创建充值订单（支持套餐充值和自定义充值）
     */
    public function createOrder()
    {
        try {
            $user = $this->request->user;
            if (!$user) {
                return json(['code' => 401, 'msg' => '用户未登录']);
            }

            $packageId = $this->request->param('package_id/d');
            $points = $this->request->param('points/d');

            // 验证参数：套餐ID和积分数量至少需要一个
            if (!$packageId && !$points) {
                return json([
                    'code' => 400,
                    'msg' => '请选择充值套餐或输入充值积分数量'
                ]);
            }

            $result = $this->rechargeService->createOrder($user->uid, $packageId, $points);

            return json([
                'code' => 200,
                'msg' => '订单创建成功',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 微信支付回调处理
     */
    public function notify()
    {
        try {
            // 直接写入文件测试
            file_put_contents(runtime_path() . 'notify_test.log', date('Y-m-d H:i:s') . ' - 收到回调' . PHP_EOL, FILE_APPEND);
            
            $app = $this->rechargeService->getPayApp();
            
            $response = $app->handleScannedNotify(function($message, $fail, $alert) {
                file_put_contents(runtime_path() . 'notify_test.log', date('Y-m-d H:i:s') . ' - 进入回调处理' . json_encode($message) . PHP_EOL, FILE_APPEND);
                
                // 处理回调
                $result = $this->rechargeService->handleNotify($message);
                
                file_put_contents(runtime_path() . 'notify_test.log', date('Y-m-d H:i:s') . ' - 处理结果：' . ($result ? '成功' : '失败') . PHP_EOL, FILE_APPEND);
                
                return $result ? true : $fail('处理失败');
            });

            return $response;

        } catch (\Exception $e) {
            file_put_contents(runtime_path() . 'notify_test.log', date('Y-m-d H:i:s') . ' - 异常：' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            // 返回微信需要的XML格式错误响应
            $xml = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[' . $e->getMessage() . ']]></return_msg></xml>';
            return Response::create($xml, 'xml');
        }
    }

    /**
     * 查询订单状态
     */
    public function queryOrder()
    {
        try {
            $user = $this->request->user;
            if (!$user) {
                return json(['code' => 401, 'msg' => '用户未登录']);
            }

            $orderNo = $this->request->param('order_no/s');
            if (empty($orderNo)) {
                return json([
                    'code' => 400,
                    'msg' => '订单号不能为空'
                ]);
            }

            // 查询用户的订单（增加用户ID验证，防止查询其他用户订单）
            $order = $this->rechargeService->queryOrder($orderNo, $user->uid);
            
            if (!$order) {
                return json([
                    'code' => 404,
                    'msg' => '订单不存在'
                ]);
            }

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $order
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取用户充值记录
     */
    public function getOrderList()
    {
        try {
            $user = $this->request->user;
            if (!$user) {
                return json(['code' => 401, 'msg' => '用户未登录']);
            }

            $page = $this->request->param('page/d', 1);
            $pageSize = $this->request->param('pageSize/d', 10);

            $orders = $this->rechargeService->getUserOrders($user->uid, $page, $pageSize);

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'list' => $orders,
                    'page' => $page,
                    'pageSize' => $pageSize
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 检查订单支付状态（用于前端轮询）
     */
    public function checkOrderStatus()
    {
        try {
            $user = $this->request->user;
            if (!$user) {
                return json(['code' => 401, 'msg' => '用户未登录']);
            }

            $orderNo = $this->request->param('order_no/s');
            if (empty($orderNo)) {
                return json([
                    'code' => 400,
                    'msg' => '订单号不能为空'
                ]);
            }

            $order = $this->rechargeService->queryOrder($orderNo, $user->uid);
            
            if (!$order) {
                return json([
                    'code' => 404,
                    'msg' => '订单不存在'
                ]);
            }

            // 返回简化的状态信息
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'order_no' => $order['order_no'],
                    'status' => $order['status'],
                    'status_text' => $order['status_text'],
                    'is_paid' => in_array($order['status'], [1, 2]), // 已支付或已完成
                    'points' => $order['points'],
                    'price' => $order['price']
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 